package io.ticktick.modules.app.controller;

import io.ticktick.common.utils.R;
import io.ticktick.modules.app.entity.UserEntity;
import io.ticktick.modules.app.form.LoginForm;
import io.ticktick.modules.app.service.UserService;
import io.ticktick.modules.app.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("app/user")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("login")
    public R login(@RequestBody LoginForm form) {
        //表单校验
//        ValidatorUtils.validateEntity(form);

        //用户登录
        long userId = userService.login(form);

        UserEntity userEntity = userService.getById(userId);

        //账号锁定
        if (userEntity.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }
        //生成token
        String token = jwtUtils.generateToken(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        return R.ok(map);
    }

}
